<template>
  <div class="operate-record">
    <div class="search">
      <el-form :model="searchForm" label-position="top">
        <el-form-item label="类型" prop="operateType" style="margin-right: 10px">
          <el-select-v2
            v-model="searchForm.operateType"
            filterable
            placeholder="请选择"
            clearable
            @change="quickQuery"
            :options="operateType"
          />
        </el-form-item>
        <el-form-item label="操作人" prop="operateUser">
          <el-select-v2
            v-model="searchForm.operateUser"
            filterable
            placeholder="请选择"
            clearable
            @change="quickQuery"
            :options="getOperator"
          />
        </el-form-item>
      </el-form>
      <el-button @click="quickQuery">查询</el-button>
    </div>
    <Record
      v-if="recordData && recordData.length"
      ref="Record"
      style="height: 100%"
      :data="recordData"
      :moreShow="moreShow"
      @loadMore="loadMore"
    />
    <div v-else class="none">
      <img src="@common/assets/empty.svg" alt="" />
      <p>暂无操作日志</p>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, toRefs } from 'vue'
import Record from './record.vue'
import { opeLog } from '@app/customer/apis/pool'
import { commonStore } from '@/common/store/modules/common'
import { encryptPhone } from '@/common/utils/common'
import { getGender } from '@app/customer/utils/common'
interface State {
  recordData: Record<string, unknown>[]
  searchForm: Record<string, unknown>
  pageData: Record<string, number>
  operateType: Record<string, unknown>[]
  moreShow: boolean
}
export default defineComponent({
  name: 'OperateLog',
  components: { Record },
  props: {
    customerId: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const state: State = reactive({
      recordData: [],
      searchForm: {},
      pageData: {
        page: 1,
        limit: 10,
        total: 0
      },
      moreShow: false,
      operateType: [
        {
          value: 'create_customer_single_no_assign',
          label: '单条录入-不分配'
        },
        {
          value: 'create_customer_single_assign',
          label: '单条录入-分配到人员'
        },
        {
          value: 'manual_assign',
          label: '手动分配'
        },
        {
          value: 'incoming_auto_create',
          label: '来电自动保存'
        },
        {
          value: 'update_customer',
          label: '更改客户信息'
        },
        {
          value: 'cdr_assign_customer',
          label: '关联客户'
        },
        {
          value: 'cancel_assign_cdr_customer',
          label: '取消关联'
        }
      ]
    })

    const getOperator = computed(() => {
      const arr = commonStore().publicCache.userCache || []
      return arr.map((v: any) => {
        return {
          label: v.agentName + '[' + v.agentNumber + ']',
          value: v._id
        }
      })
    })

    const areaMap: any = computed(() => {
      return commonStore().publicCache.areaMap || {}
    })

    const getAgentName = (id: string) => {
      const obj = commonStore().publicCache.userCacheObj[id] || {}
      if (obj.agentName) {
        return obj.agentName + '[' + obj.agentNumber + ']'
      }
      return ''
    }

    const clearSearchForm = () => {
      state.searchForm = {
        operateType: '',
        operateUser: ''
      }
    }

    const loadMore = () => {
      const { total, page, limit } = state.pageData
      if (total > page * limit) {
        state.pageData.page++
        getLogs()
      }
    }

    const getOperateTypeName = (id: any) => {
      const types: any = {}
      state.operateType.map((item: any) => {
        types[item.value] = item.label
      })
      return types[id]
    }

    const getLabel = (key: any) => {
      const labels: any = {
        owner: '分配给',
        importBatchNumber: '导入批次'
      }

      if (labels[key]) {
        return labels[key]
      }

      return ''
    }

    const getLogs = () => {
      const { page, limit } = state.pageData
      const sendData = {
        page,
        limit,
        customerId: props.customerId,
        operateUser: state.searchForm.operateUser,
        operateType: state.searchForm.operateType
      }
      opeLog(sendData).then((res) => {
        if (res.success && res.data) {
          res.data.list.map((item: any) => {
            item.name = getAgentName(item.createAgent)
            item.operateName = getOperateTypeName(item.operateType)
            if (['manual_assign', 'create_customer_single_assign', 'incoming_auto_create'].includes(item.operateType)) {
              item.isUpdate = 'change'
              if (item.changes && item.changes.length) {
                item.changes.map((it: any) => {
                  it.label = getLabel(it.fieldKey)
                  if (it.fieldId === 'updateAgent') {
                    // 客户更新人
                    it.newValue = getAgentName(it.newValue)
                    it.oldValue = getAgentName(it.oldValue)
                  }
                })
              }
            } else if (['update_customer'].includes(item.operateType)) {
              item.isUpdate = 'change'
              if (item.changes && item.changes.length) {
                item.changes.map((it: any) => {
                  it.label = it.fieldKey
                  if (it.fieldId === 'region') {
                    // 省市区
                    if (it.newValue && it.newValue.length) {
                      it.newValue = it.newValue.map((v: string | number) => {
                        return areaMap.value[v]
                      })
                    }
                    if (it.oldValue && it.oldValue.length) {
                      it.oldValue = it.oldValue.map((v: string | number) => {
                        return areaMap.value[v]
                      })
                    }
                  } else if (it.fieldType === 'pairs') {
                    it.type = 'pairs'
                    if ((it.newValue && it.newValue.length) >= (it.oldValue && it.oldValue.length)) {
                      it.isNew = true // 根据长度判断 -> 的显示
                    } else {
                      it.isNew = false // 根据长度判断 -> 的显示
                    }
                    // 文本数组
                    if (it.fieldId === 'mobile') {
                      it.newValue =
                        it.newValue &&
                        it.newValue.map((mo: any) => {
                          return {
                            value: encryptPhone(mo.value),
                            memo: mo.memo
                          }
                        })
                      it.oldValue =
                        it.oldValue &&
                        it.oldValue.map((mo: any) => {
                          return {
                            value: encryptPhone(mo.value),
                            memo: mo.memo
                          }
                        })
                    }
                  } else if (it.fieldId === 'gender') {
                    // 性别
                    it.newValue = getGender[it.newValue] || ''
                    it.oldValue = getGender[it.oldValue] || ''
                  } else if (it.fieldId === 'updateAgent') {
                    // 客户更新人
                    it.newValue = getAgentName(it.newValue)
                    it.oldValue = getAgentName(it.oldValue)
                  }
                })
              }
            } else if (['cdr_assign_customer', 'cancel_assign_cdr_customer'].includes(item.operateType)) {
              item.isUpdate = 'relation'
              item.changes.map((it: any) => {
                if (it.fieldId === 'updateAgent') {
                  // 客户更新人
                  it.newValue = getAgentName(it.newValue)
                  it.oldValue = getAgentName(it.oldValue)
                }
              })
            }
          })
          state.recordData = state.recordData.concat(res.data.list)
          state.pageData.total = res.data.count || 0
          if (state.pageData.total > limit * page) {
            state.moreShow = true
          } else {
            state.moreShow = false
          }
        }
      })
    }

    const quickQuery = () => {
      state.pageData.page = 1
      state.recordData = []
      getLogs()
    }

    return {
      ...toRefs(state),
      getLogs,
      getOperator,
      clearSearchForm,
      loadMore,
      quickQuery
    }
  }
})
</script>

<style lang="stylus" scoped>
.operate-record
  width 100%
  height 100%
  .search
    display flex
    justify-content space-between
    align-items center
    .el-form
      display flex
  .none
    text-align center
    color rgba(0, 0, 0, .6)
    margin-top 50px
</style>
